#pragma once

#define BUFFER_SIZE (1024 * 16)

struct XBuff
{
    int     nLeftSize;
    void*   pvBuff;
    void*   pvPos;
    XBuff*  pNext;

    XBuff(int nSize = BUFFER_SIZE)
    {
        nLeftSize   = nSize;
        pvBuff      = malloc(nSize);
        pvPos       = pvBuff;
        pNext       = NULL;
    }

    ~XBuff()
    {
        free(pvBuff);
    }

};

static void* GetBuff(XBuff* pBuff, int nSize)
{
    void*   pData   = NULL;

    assert(pBuff);

    while (pBuff->pNext)
    {
        pBuff = pBuff->pNext;
    }

    if (pBuff->nLeftSize < nSize)
    {
        XBuff* pNewBuff = new XBuff(BUFFER_SIZE > nSize ? BUFFER_SIZE : nSize);
        pBuff->pNext = pNewBuff;
        pBuff = pBuff->pNext;
    }

    pData = pBuff->pvPos;

    pBuff->pvPos        = (char*)pBuff->pvPos + nSize;
    pBuff->nLeftSize   -= nSize;

    return pData;
}

static void DeleteBuff(XBuff* pBuff)
{
    XBuff* pNextBuff = NULL;
    while (pBuff)
    {
        pNextBuff = pBuff->pNext;
        delete pBuff;
        pBuff = pNextBuff;
    }
}